package com.itheima.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    //将map模拟为一个数据库
    private Map map = new HashMap<String,User>();

    private void init(){

        User user1 = new User();
        user1.setUsername("zhangsan");
        user1.setPassword(passwordEncoder.encode("1234"));

        User user2 = new User();
        user2.setUsername("lisi");
        user2.setPassword(passwordEncoder.encode("1234"));

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);

    }

    /**
     *
     * @param username：是当用户在登录页面提交数据时，会调用该loadUserByUsername方法，而其中的username参数就是登陆页面中提交的登陆用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //模拟初始化数据库
        init();

        //从数据库中获取用户信息
        User user = (User) map.get(username);

        //给用户设置授权
        List<GrantedAuthority> list = new ArrayList<>();
        /**
         * 授予角色的规则：
         *  必须携带ROLE_前缀，并全部大写，比如ROLE_ADMIN,ROLE_MANAGER
         *
         *  add表示给用户设置权限：权限不需要添加ROLE_的前缀，并大小写都可
         *
         */
        if (user.getUsername().equals("zhangsan")){
            list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            list.add(new SimpleGrantedAuthority("add"));
            list.add(new SimpleGrantedAuthority("ROLE_MANAGE"));
        }


        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list);
    }

    /*public static void main(String[] args) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode1 = passwordEncoder.encode("1234");
        String encode2 = passwordEncoder.encode("1234");
        System.out.println(encode1);
        System.out.println(encode2);

        boolean flag1 = passwordEncoder.matches("1234", encode1);
        boolean flag2 = passwordEncoder.matches("1234", encode2);
        System.out.println(flag1);
        System.out.println(flag2);

    }*/
}
